package com.ruoyi.report_jl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.report_gc.domain.bo.GcjxljjtbgBsInfoBo;
import com.ruoyi.report_jl.domain.vo.ReportJlCjllmysybgRefVo;
import com.ruoyi.report_jl.domain.vo.ReportJlCjlsfssfjlbBaDetailVo;
import com.ruoyi.report_jl.mapper.ReportJlCjlbgBaDetailMapper;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.syrw.annotation.FIllBasicInfoForTaiZhang;
import com.ruoyi.report_tg.domain.TgsybgBaDetail;
import com.ruoyi.report_tg.domain.vo.TgsybgBaDetailVo;
import com.ruoyi.report_tg.mapper.TgsybgBaDetailMapper;
import com.ruoyi.sycs.service.IBiQualificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_jl.domain.bo.ReportJlCjllmysybgBsInfoBo;
import com.ruoyi.report_jl.domain.vo.ReportJlCjllmysybgBsInfoVo;
import com.ruoyi.report_jl.domain.ReportJlCjllmysybgBsInfo;
import com.ruoyi.report_jl.mapper.ReportJlCjllmysybgBsInfoMapper;
import com.ruoyi.report_jl.service.IReportJlCjllmysybgBsInfoService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 粗集料试验检测报告(路面用）-对应水筛法Service业务层处理
 *
 * @author tll
 * @date 2024-05-23
 */
@RequiredArgsConstructor
@Service
public class ReportJlCjllmysybgBsInfoServiceImpl implements IReportJlCjllmysybgBsInfoService {

    private final ReportJlCjllmysybgBsInfoMapper baseMapper;
    private final ReportJlCjlbgBaDetailMapper reportJlCjlbgBaDetailMapper;

    private final TgsybgBaDetailMapper detailMapper;

    private static final Long[] keys = {160L, 162L, 161L, 35L, 36L, 37L, 21L, 159L, 25L, 27L, 38L};

    private final IBiQualificationService biQualificationService;

    /**
     * 查询粗集料试验检测报告(路面用）-对应水筛法
     */
    @Override
    @FIllBasicInfo
    public ReportJlCjllmysybgBsInfoVo queryById(Long excelId){
        // 主表
        ReportJlCjllmysybgBsInfoVo vo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<TgsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<TgsybgBaDetail>()
            .eq(TgsybgBaDetail::getExcelId, excelId).orderByAsc(TgsybgBaDetail::getId));
        baDetailVos.forEach(v->{
            v.setQualInfo(biQualificationService.queryById(v.getQualId()));
        });
        // 格式化 技术指标
        biQualificationService.compute(baDetailVos);
        // 转换成map形式
        Map<Long, TgsybgBaDetailVo> collect = baDetailVos.stream().collect(Collectors.toMap(TgsybgBaDetailVo::getQualId, v -> {
            return v;
        }));
        vo.setBaDetailVos(collect);
        List<ReportJlCjllmysybgRefVo> ssfs = new ArrayList<>(16);
        // 最大值 最小值
//        String[] maxs = new String[]{"100","90",null,null,null,null,"15","5",null,null};
//        String[] mims = new String[]{"100","100",null,null,null,null,"0","0",null,null};
        String[] maxs = new String[]{null,null,null,null,null,null,null,null,null,null};
        for (int i=0; i< maxs.length; i++) {
            ReportJlCjllmysybgRefVo refVo = new ReportJlCjllmysybgRefVo();
//            refVo.setMax(maxs[i]);
//            refVo.setMin(mims[i]);
            ssfs.add(refVo);
        }
        // 水筛-筛孔尺寸 通过百分率
        List<ReportJlCjlsfssfjlbBaDetailVo> list = baseMapper.getDetailRelainfo(excelId);
        for (int i=0; i<ssfs.size(); i++) {
            if (i<list.size()) {
                if (ObjectUtils.isNotEmpty(list.get(i))) {
                    ssfs.get(i).setSkcc(list.get(i).getShaikcc());
                    ssfs.get(i).setScz(list.get(i).getTonggbflPjz());
                    ssfs.get(i).setMin(ObjectUtils.isNotEmpty(list.get(i).getGuidfwMin()) ? list.get(i).getGuidfwMin().toString() : null);
                    ssfs.get(i).setMax(ObjectUtils.isNotEmpty(list.get(i).getGuidfwMax()) ? list.get(i).getGuidfwMax().toString() : null);
                }
            }
        }
        vo.setSsfs(ssfs);
        // 子表
//        LambdaQueryWrapper<ReportJlCjlbgBaDetail> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(excelId != null, ReportJlCjlbgBaDetail::getExcelId, excelId);
//        lqw.orderByAsc(ReportJlCjlbgBaDetail::getCreateTime);
//        List<ReportJlCjlbgBaDetailVo> detailList = reportJlCjlbgBaDetailMapper.selectVoList(lqw);
//        vo.setDetailList(detailList);
        return vo;
    }

    @Override
    @FIllBasicInfoForTaiZhang
    public ReportJlCjllmysybgBsInfoVo queryByIdForTaizhang(Long excelId) {
        // 主表
        ReportJlCjllmysybgBsInfoVo vo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<TgsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<TgsybgBaDetail>()
            .eq(TgsybgBaDetail::getExcelId, excelId).orderByAsc(TgsybgBaDetail::getId));
        baDetailVos.forEach(v->{
            v.setQualInfo(biQualificationService.queryById(v.getQualId()));
        });
        // 格式化 技术指标
        biQualificationService.compute(baDetailVos);
        // 转换成map形式
        Map<Long, TgsybgBaDetailVo> collect = baDetailVos.stream().collect(Collectors.toMap(TgsybgBaDetailVo::getQualId, v -> {
            return v;
        }));
        vo.setBaDetailVos(collect);
        List<ReportJlCjllmysybgRefVo> ssfs = new ArrayList<>(16);
        // 最大值 最小值
//        String[] maxs = new String[]{"100","90",null,null,null,null,"15","5",null,null};
//        String[] mims = new String[]{"100","100",null,null,null,null,"0","0",null,null};
        String[] maxs = new String[]{null,null,null,null,null,null,null,null,null,null};
        for (int i=0; i< maxs.length; i++) {
            ReportJlCjllmysybgRefVo refVo = new ReportJlCjllmysybgRefVo();
//            refVo.setMax(maxs[i]);
//            refVo.setMin(mims[i]);
            ssfs.add(refVo);
        }
        // 水筛-筛孔尺寸 通过百分率
        List<ReportJlCjlsfssfjlbBaDetailVo> list = baseMapper.getDetailRelainfo(excelId);
        for (int i=0; i<ssfs.size(); i++) {
            if (i<list.size()) {
                if (ObjectUtils.isNotEmpty(list.get(i))) {
                    ssfs.get(i).setSkcc(list.get(i).getShaikcc());
                    ssfs.get(i).setScz(list.get(i).getTonggbflPjz());
                    ssfs.get(i).setMin(ObjectUtils.isNotEmpty(list.get(i).getGuidfwMin()) ? list.get(i).getGuidfwMin().toString() : null);
                    ssfs.get(i).setMax(ObjectUtils.isNotEmpty(list.get(i).getGuidfwMax()) ? list.get(i).getGuidfwMax().toString() : null);
                }
            }
        }
        vo.setSsfs(ssfs);
        // 子表
//        LambdaQueryWrapper<ReportJlCjlbgBaDetail> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(excelId != null, ReportJlCjlbgBaDetail::getExcelId, excelId);
//        lqw.orderByAsc(ReportJlCjlbgBaDetail::getCreateTime);
//        List<ReportJlCjlbgBaDetailVo> detailList = reportJlCjlbgBaDetailMapper.selectVoList(lqw);
//        vo.setDetailList(detailList);
        return vo;
    }

    /**
     * 查询粗集料试验检测报告(路面用）-对应水筛法列表
     */
    @Override
    public TableDataInfo<ReportJlCjllmysybgBsInfoVo> queryPageList(ReportJlCjllmysybgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ReportJlCjllmysybgBsInfo> lqw = buildQueryWrapper(bo);
        Page<ReportJlCjllmysybgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询粗集料试验检测报告(路面用）-对应水筛法列表
     */
    @Override
    public List<ReportJlCjllmysybgBsInfoVo> queryList(ReportJlCjllmysybgBsInfoBo bo) {
        LambdaQueryWrapper<ReportJlCjllmysybgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ReportJlCjllmysybgBsInfo> buildQueryWrapper(ReportJlCjllmysybgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ReportJlCjllmysybgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTotalPage() != null, ReportJlCjllmysybgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(bo.getPage() != null, ReportJlCjllmysybgBsInfo::getPage, bo.getPage());
        lqw.eq(StringUtils.isNotBlank(bo.getJilbh()), ReportJlCjllmysybgBsInfo::getJilbh, bo.getJilbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), ReportJlCjllmysybgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), ReportJlCjllmysybgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), ReportJlCjllmysybgBsInfo::getYangpmc, bo.getYangpmc());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), ReportJlCjllmysybgBsInfo::getYangpbh, bo.getYangpbh());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), ReportJlCjllmysybgBsInfo::getYangpsl, bo.getYangpsl());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), ReportJlCjllmysybgBsInfo::getYangpzt, bo.getYangpzt());
        lqw.eq(bo.getYangpsj() != null, ReportJlCjllmysybgBsInfo::getYangpsj, bo.getYangpsj());
        lqw.eq(StringUtils.isNotBlank(bo.getShiyjcrq()), ReportJlCjllmysybgBsInfo::getShiyjcrq, bo.getShiyjcrq());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), ReportJlCjllmysybgBsInfo::getShiytjwd, bo.getShiytjwd());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), ReportJlCjllmysybgBsInfo::getShiytjsd, bo.getShiytjsd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), ReportJlCjllmysybgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), ReportJlCjllmysybgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), ReportJlCjllmysybgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), ReportJlCjllmysybgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getBaobmc()), ReportJlCjllmysybgBsInfo::getBaobmc, bo.getBaobmc());
        lqw.eq(StringUtils.isNotBlank(bo.getBaobbh()), ReportJlCjllmysybgBsInfo::getBaobbh, bo.getBaobbh());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), ReportJlCjllmysybgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), ReportJlCjllmysybgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), ReportJlCjllmysybgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancr()), ReportJlCjllmysybgBsInfo::getJiancr, bo.getJiancr());
        lqw.eq(StringUtils.isNotBlank(bo.getJilr()), ReportJlCjllmysybgBsInfo::getJilr, bo.getJilr());
        lqw.eq(StringUtils.isNotBlank(bo.getFuhr()), ReportJlCjllmysybgBsInfo::getFuhr, bo.getFuhr());
        lqw.eq(bo.getRiq() != null, ReportJlCjllmysybgBsInfo::getRiq, bo.getRiq());
        lqw.eq(StringUtils.isNotBlank(bo.getQuydd()), ReportJlCjllmysybgBsInfo::getQuydd, bo.getQuydd());
        lqw.eq(bo.getJincrq() != null, ReportJlCjllmysybgBsInfo::getJincrq, bo.getJincrq());
        lqw.eq(bo.getDaibsl() != null, ReportJlCjllmysybgBsInfo::getDaibsl, bo.getDaibsl());
        lqw.eq(StringUtils.isNotBlank(bo.getChand()), ReportJlCjllmysybgBsInfo::getChand, bo.getChand());
        lqw.eq(bo.getRefExcelId() != null, ReportJlCjllmysybgBsInfo::getRefExcelId, bo.getRefExcelId());
        return lqw;
    }

    /**
     * 新增粗集料试验检测报告(路面用）-对应水筛法
     */
    @Override
    public Boolean insertByBo(ReportJlCjllmysybgBsInfoBo bo) {
        ReportJlCjllmysybgBsInfo add = BeanUtil.toBean(bo, ReportJlCjllmysybgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            // 新增详细 多个keys
//            ArrayList<TgsybgBaDetail> details = new ArrayList<>(15);
            for (Long key : keys) {
//                details.add(new TgsybgBaDetail(add.getExcelId(), key));
                detailMapper.insert(new TgsybgBaDetail(add.getExcelId(), key));
            }
//            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改粗集料试验检测报告(路面用）-对应水筛法
     */
    @Override
    public Boolean updateByBo(ReportJlCjllmysybgBsInfoBo bo) {
        // 增加对 是否合格 的填充
        fillExcelResult(bo);
        // 主表
        ReportJlCjllmysybgBsInfo update = BeanUtil.toBean(bo, ReportJlCjllmysybgBsInfo.class);
        validEntityBeforeSave(update);
//        boolean upd = baseMapper.updateById(update) > 0;
//        // 子表
//        boolean upd2 = false;
//        boolean insert = false;
//        if (ObjectUtils.isNotEmpty(bo.getDetailList())) {
//            for (ReportJlCjlbgBaDetail det : bo.getDetailList()) {
//                if (ObjectUtils.isNotEmpty(det.getDetailId())) {
//                    // 修改
//                    upd2 = reportJlCjlbgBaDetailMapper.updateById(det) > 0;
//                } else {
//                    // 新增
//                    insert = reportJlCjlbgBaDetailMapper.insert(det) > 0;
//                }
//            }
//        }
//        return upd && upd2 && insert;

        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos().values(), TgsybgBaDetail.class));
        }
        return flag;
    }

    private void fillExcelResult(ReportJlCjllmysybgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
            for (TgsybgBaDetailVo detailVo : bo.getBaDetailVos().values()) {
                if ("不符合".equals(detailVo.getJiegpd())) {
                    bo.setExcelResult(2);
                    return;
                }
            }
            bo.setExcelResult(1);
        }
        bo.setExcelResult(0);
    }

    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ReportJlCjllmysybgBsInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除粗集料试验检测报告(路面用）-对应水筛法
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
